package com.mojo.concurrent.container;

import com.mojo.concurrent.concurrent_01_thread.Profiler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Fork/Join框架
 * 大任务fork成多个小任务，然后join得到最终结果
 * 充分利用线程进行并行计算，减少线程间的竞争
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/16 15:24
 */
public class ForkJoin01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Profiler.begin();
        int sum = 0;
        for (int i = 0; i < 1000000; i++) {
            sum += i;
        }
        System.out.println(sum);
        System.out.println("单线程总耗时毫秒数：" + Profiler.interval() + "ms");
        System.out.println("=============================================");
        Profiler.begin();
        CountTask countTask = new CountTask(0, 1000000);
        ForkJoinPool joinPool = new ForkJoinPool();
        ForkJoinTask<Integer> task = joinPool.submit(countTask);
        System.out.println(task.get());
        System.out.println("Fork/Join总耗时毫秒数：" + Profiler.interval() + "s");
    }


    static class CountTask extends RecursiveTask<Integer> {
        public static final int THRESHOLD = 10000;
        int start;
        int end;

        public CountTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            boolean canCompute = (end - start) <= THRESHOLD;
            // 是否fork判断
            int sum = 0;
            if (canCompute) {
                for (int i = start; i <= end; i++) {
                    sum += i;
                }
            } else {
                //   重新fork
                int middle = (start + end) / 2;
                CountTask leftTask = new CountTask(start, middle);
                CountTask rightTask = new CountTask(middle + 1, end);
                // fork方法
                leftTask.fork();
                rightTask.fork();
                // join结果
                Integer leftCount = leftTask.join();
                Integer rightCount = rightTask.join();
                sum = leftCount + rightCount;

            }
            return sum;
        }
    }
}
